<template>
  <UniPopup
    ref="customSharePopupRef"
    backgroundColor="#fff"
    borderRadius="32rpx 32rpx 0 0"
    type="bottom"
    :isMaskClick="false"
    :zIndex="zIndex"
    @maskClick="maskClick"
  >
    <view class="container">
      <scroll-view
        scroll-x
        :enable-flex="true"
        scroll-with-animation
        scroll-anchoring
        :enhanced="true"
        :show-scrollbar="false"
        style="width: 100%"
      >
        <view class="btn-list disFlx">
          <template v-for="(item, index) in getShareBtnList" :key="index">
            <view
              v-if="item.type !== CustomShareTypeEnum.INTERNAL_LINKS || userInfo.sysUserId"
              class="disFlxCC btn-item flex-shrink-0"
              @click="handleItemClick(item)"
            >
              <TImage :src="item.icon" width="88rpx" height="88rpx" />
              <text class="mt-8 fz-12">{{ item.text }}</text>
            </view>
          </template>
        </view>
      </scroll-view>
      <view class="tieku"></view>
      <view class="h-48 fz-16 disFlxAC disFlxJC" @click="emits('update:visible', false)">
        <text>取消</text>
      </view>
    </view>
  </UniPopup>

  <UniPopup ref="sharePopupRef" :zIndex="zIndex">
    <view style="width: 100vw">
      <WxshareSwiper v-model="wxShareSwiperCurrent" :list="wxShareList" />
    </view>
  </UniPopup>

  <UniPopup ref="posterPopupRef" :zIndex="zIndex">
    <view style="width: 100vw">
      <PosterShareSwiper :list="posterShareList" />
    </view>
  </UniPopup>

  <UniPopup ref="momentsPopupRef" type="top" :zIndex="zIndex">
    <view style="width: 100vw; padding-top: 200rpx">
      <TImage
        src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/share-guide-icon.png"
        width="444rpx"
        height="316rpx"
      />
    </view>
  </UniPopup>

  <UniPopup ref="shortLinkPopupRef" type="top" :zIndex="zIndex">
    <view style="width: 100vw; padding-top: 200rpx">
      <TImage
        src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/share-guide-icon2.png"
        width="444rpx"
        height="316rpx"
      />
    </view>
  </UniPopup>

  <UniPopup
    ref="copyLinkPopupRef"
    type="bottom"
    backgroundColor="#fff"
    borderRadius="32rpx 32rpx 0 0"
    :zIndex="zIndex"
  >
    <view>
      <view class="px-16 py-12">
        <text class="fz-16">复制链接</text>
      </view>
      <view class="px-16 pt-16 disFlx">
        <template v-for="(item, index) in copyLinkList" :key="index">
          <view
            class="copy-link-item flex-1 br-8 disFlxCC mr-4 py-8"
            :class="{ 'copy-link-item--active': copyLinkCurrent === item.type }"
            @click="handleSelectedCopyLink(item.type)"
          >
            <view
              v-if="disabledsRef?.shortLink && item.type === 'ShortLink'"
              class="disabled-model disFlxCC fz-14 br-8"
            >
              <text>暂不支持此链接</text>
            </view>
            <view class="mb-8 disFlxAC">
              <text
                v-if="copyLinkCurrent === item.type"
                class="ali-icon fz-20"
                style="color: #2878ff"
              >
                &#xe693;
              </text>
              <text v-else class="ali-icon fz-20">&#xe690;</text>
              <text class="ml-8 fz-14">{{ item.text }}</text>
            </view>
            <view class="fz-12 mb-8" style="color: #969799">
              <text>{{ item.tips }}</text>
            </view>
            <TImage :src="item.img" width="320rpx" height="320rpx" border-radius="8rpx" />
          </view>
        </template>
      </view>
      <view class="px-16 pb-16 mt-8 fz-12" style="color: #969799; text-align: right">
        <text>*暂不支持PC端打开小程序</text>
      </view>
      <view class="px-16 py-10">
        <TButtonGroup position="unset" :styles="{ padding: 0 }">
          <TButton
            text="取消"
            type="none"
            class="gutter-btn"
            custom-class="h-44 linh-44 br-22 px-16"
            :custom-style="{
              color: '#2878FF',
              border: '1px solid #2878FF',
              boxSizing: 'content-box',
            }"
            @click="closePopup('copyLinkPopupRef')"
          />
          <TButton
            text="复制"
            type="primary"
            class="gutter-btn"
            custom-class="h-44 linh-44 br-22 px-16"
            @click="handleCopyLink"
          />
        </TButtonGroup>
      </view>
    </view>
  </UniPopup>

  <LPainter ref="painterRef" custom-style="position: fixed; left: -2000px" />
  <TencentCode :popupShow="tencentCodeShow" @close="tencentCodeClose" />
</template>

<script setup lang="ts">
  import LPainter from '@/uni_modules/lime-painter/components/l-painter/l-painter.vue';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import TencentCode from '@/components/OfficialAccount/tencentCode.vue';
  import TImage from '@/components/TImage/index.vue';
  import WxshareSwiper from './components/WxshareSwiper.vue';
  import PosterShareSwiper from './components/PosterShareSwiper.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { createURLlink } from '@/api';
  import { propTypes } from '@/utils/propTypes';
  import { computed, getCurrentInstance, watch, ref, onMounted } from 'vue';
  import {
    CustomShareTypeEnum,
    type CustomShareActionType,
    type ShareBtnItem,
    type WxShareOptions,
    type ReturnWxShareOptions,
    type CopyLinkItem,
  } from './types';
  import { customShareButtons, type CustomShareOptions } from './hooks/useCustomShare';
  import { renderPainterToImage } from './utils';
  import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
  import { getUrl, navigateTo } from '@/router';
  import { TabbarPageEnum } from '@/enums/pageEnum';
  import { Toast } from '@/utils';
  import { createShareQueryStr } from '@/hooks/core/useAppShare';
  import { isShareMenu } from '@/utils/is';
  import { useUserStore } from '@/store/modules/user';
  import { isNull, isString, isUndefined } from 'lodash-es';
  import { ShareButtonId } from '@/enums/shareEnum';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import { useSaveFile } from '@/hooks/core/useSaveFile';

  const _this = getCurrentInstance();
  const painterRef = ref<Nullable<LPainterRef>>(null);
  const shareLogIdRef = ref<number>();
  const { userInfo } = useUserStore();
  const { downloadFile } = useSaveFile();

  const props = defineProps({
    visible: propTypes.bool.def(false),
    disabledOnShareAppMessage: propTypes.bool.def(false),
    zIndex: propTypes.number.def(998),
  });

  const emits = defineEmits<{
    (e: 'update:visible', type: boolean): void;
    (e: 'register', type: CustomShareActionType): void;
  }>();

  watch(
    () => props.visible,
    (val) => (val ? openPopup('customSharePopupRef') : closePopup('customSharePopupRef')),
  );

  const openPopup = (ref: string, isShowMask: boolean = true) => {
    let dom = _this?.refs[ref] as any;
    if (!isShowMask) dom.closeMask();
    dom.open();
  };

  const closePopup = (ref: string) => {
    let dom = _this?.refs[ref] as any;
    dom.close();
  };

  function maskClick() {
    // emits('update:visible', false);
  }

  function hasShareLogId() {
    const id = shareLogIdRef.value;
    if (id) return true;
    Toast('请先获取分享日志id');
    return false;
  }

  function handleItemClick(item: ShareBtnItem) {
    switch (item.type) {
      case CustomShareTypeEnum.SHARE:
        openPopup('sharePopupRef');
        break;
      case CustomShareTypeEnum.POSTER:
        openPopup('posterPopupRef');
        break;
      case CustomShareTypeEnum.TIME_LINE:
        openPopup('momentsPopupRef');
        break;
      case CustomShareTypeEnum.COPY_LINK:
        openPopup('copyLinkPopupRef');
        break;
      case CustomShareTypeEnum.INSERT_OFFIACCOUNT:
        if (!hasShareLogId()) return;
        navigateTo({
          name: 'insertMpTutorials',
          options: {
            query: {
              scene: shareLogIdRef.value?.toString() || '',
            },
          },
        });
        break;
      case CustomShareTypeEnum.OFFIACCOUNT:
        tencentCodeShow.value = true;
        break;
      case CustomShareTypeEnum.INTERNAL_LINKS:
        copyInternalLinks();
        break;
      case CustomShareTypeEnum.DOWNLOAD_MINIPROGRAM_CODE:
        downloadMiniprogramCode();
        break;
    }
  }

  const internalLinkOptions = ref<Recordable>();
  /** 复制站内链接 */
  function copyInternalLinks() {
    if (!internalLinkOptions.value) return Toast('内部链接参数为空');
    const { name, options } = internalLinkOptions.value;
    let url = getUrl(name, options);

    if (url[url.length - 1] === '?') url = url.substring(0, url.length - 1);

    uni.setClipboardData({
      data: url,
      success: () => Toast('复制成功'),
    });
  }

  const shareButtons = ref<CustomShareOptions['buttons']>();
  const getShareBtnList = computed(() => {
    return customShareButtons.filter((item) => shareButtons.value?.[item.type]);
  });

  function setButtons(buttons: CustomShareOptions['buttons']) {
    const hideShareMenu: string[] = [];
    if (!buttons.share) {
      hideShareMenu.push('shareAppMessage');
    }
    if (!buttons.timeline) {
      hideShareMenu.push('shareTimeline');
    }

    if (hideShareMenu.length > 0) {
      wx.hideShareMenu({
        menus: hideShareMenu,
      });
    }

    if (isUndefined(buttons.internalLinks) || isNull(buttons.internalLinks)) {
      buttons.internalLinks = true;
    }

    shareButtons.value = buttons;
  }

  const tencentCodeShow = ref(false);
  function tencentCodeClose() {
    tencentCodeShow.value = false;
  }

  const copyLinkCurrent = ref<CopyLinkItem['type']>('ShortLink');
  const copyLinkList = ref<CopyLinkItem[]>([
    {
      type: 'ShortLink',
      text: '微信内部',
      tips: '（聊天、朋友圈）',
      img: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/shortLink-img.png',
    },
    {
      type: 'URLLink',
      text: '微信外部',
      tips: '（短信、网页等场景）',
      img: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/URLLink-img.png',
    },
  ]);

  const handleSelectedCopyLink = (type: CopyLinkItem['type']) => {
    if (disabledsRef.value?.shortLink && type === 'ShortLink') return;
    copyLinkCurrent.value = type;
  };

  async function handleCopyLink() {
    if (copyLinkCurrent.value === 'ShortLink') {
      closePopup('copyLinkPopupRef');
      openPopup('shortLinkPopupRef');
    } else if (copyLinkCurrent.value === 'URLLink') {
      if (!hasShareLogId()) return;
      const res = await createURLlink({
        path: getUrl(TabbarPageEnum.STARTPAGE),
        query: createShareQueryStr({ scene: shareLogIdRef.value }),
      });
      uni.setClipboardData({
        data: res,
        success: () => Toast('复制成功'),
      });
      closePopup('copyLinkPopupRef');
    }
  }

  const wxShareList = ref<Array<ReturnWxShareOptions>>([]);
  const wxShareSwiperCurrent = ref(0);
  /** 设置微信分享的参数 */
  async function setWxShareOptions(options: WxShareOptions[]) {
    const list = [];
    for (let index = 0; index < options.length; index++) {
      const item = options[index];
      if (item.board) {
        const tempFilePath = await renderPainterToImage(painterRef.value, item.board);
        item.imageUrl = tempFilePath;
      }

      list.push({
        title: item.title,
        path: item.path,
        imageUrl: item.imageUrl,
      });
    }
    wxShareList.value = list;
    return list;
  }

  const posterShareList = ref<string[]>([]);
  const menuWxShareOptions = ref<WxShareOptions>();
  /** 设置海报绘制数据 */
  async function setPosterDrawData(data: PainterBoard[] | string[]) {
    const list = [];
    for (let index = 0; index < data.length; index++) {
      const item = data[index];
      const tempFilePath = isString(item)
        ? item
        : await renderPainterToImage(painterRef.value, item);
      list.push(tempFilePath);
    }
    posterShareList.value = list;
    return list;
  }

  const disabledsRef = ref<CustomShareOptions['disableds']>();
  function handleSetDisableds() {
    if (disabledsRef.value?.shortLink) {
      copyLinkCurrent.value = 'URLLink';
    }
  }

  const shareTimelineContent = ref<Page.ShareTimelineContent>();
  const actionType: CustomShareActionType = {
    setButtons,
    setDisableds: (disableds) => {
      disabledsRef.value = disableds;
      handleSetDisableds();
    },
    setWxShareOptions,
    setMenuWxShareOptions: (op) => (menuWxShareOptions.value = op),
    getCurrentWxShareOptions: () => wxShareList.value[wxShareSwiperCurrent.value],
    setPosterDrawData,
    setShareTimelineContent: (op) => (shareTimelineContent.value = op),
    setShareLogId: (shareLogId) => (shareLogIdRef.value = shareLogId),
    setInternalLinkOptions: (options) => (internalLinkOptions.value = options),
    setMiniprogramCode: (codeImg) => (miniprogramCode.value = codeImg),
  };

  const miniprogramCode = ref<string>();
  async function downloadMiniprogramCode() {
    uni.showLoading({ title: '二维码生成中...' });
    if (!miniprogramCode.value) {
      if (!shareLogIdRef.value) return Toast('日志ID不能为空');
      miniprogramCode.value = await createMiniCode({ shareLogId: shareLogIdRef.value });
    }
    const tempCodeImg = await downloadFile(miniprogramCode.value);
    uni.showShareImageMenu({
      path: tempCodeImg,
    });
    uni.hideLoading();
  }

  if (!props.disabledOnShareAppMessage) {
    onShareAppMessage((e) => {
      if (menuWxShareOptions.value && isShareMenu(e.from)) {
        return menuWxShareOptions.value;
      }
      if (!e.target?.id || e.target?.id === ShareButtonId.CUSTOMSHARE_BUTTON_ID) {
        const { title, path, imageUrl } = wxShareList.value[wxShareSwiperCurrent.value];
        return {
          title,
          path,
          imageUrl,
        };
      }
      return {};
    });
  }

  onShareTimeline(() => {
    closePopup('momentsPopupRef');
    return shareTimelineContent.value || {};
  });

  onMounted(() => {
    emits('register', actionType);
  });
</script>

<style lang="scss" scoped>
  .container {
    position: relative;
    color: #333333;
    .btn-list {
      height: 232rpx;
      .btn-item {
        width: 168rpx;
      }
    }
    .tieku {
      height: 16rpx;
      background-color: #f7f8fa;
    }
  }

  .copy-link-item {
    border: 1px solid #ebedf0;
    color: #333;
    position: relative;
    .disabled-model {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      z-index: 1;
      background-color: rgba(0, 0, 0, 0.7);
      color: #fff;
    }
  }
  .copy-link-item--active {
    border: 1px solid #2878ff;
  }
</style>
